package cn.lj.payment.controller.time;

import cn.lj.payment.mapper.pojo.SmallMiGoodsOrder;
import cn.lj.payment.service.bo.PayMent;
import cn.lj.payment.service.service.PayMentService;
import com.alipay.api.AlipayApiException;
import com.alipay.api.domain.AlipayTradeQueryModel;
import com.alipay.api.response.AlipayTradeQueryResponse;
import com.ijpay.alipay.AliPayApi;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;

import java.math.BigDecimal;
import java.util.List;

/**
 * @Description: ItripHotelOrderTime定时任务
 * @author: lijie
 * @date: 2021年06月26日 下午 12:00:54
 */
@Configuration
@EnableScheduling
public class SmallMiGoodsOrderTime {

    @Autowired
    private PayMentService payMentService;
    /**
     * 功能描述:
     * 每过5秒执行下面代码，查询数据库中未支付的订单并且是支付宝类型的
     * 拿到支付宝的回调号，如果是支付成功的话就把数据库的数据进行修改
     * @auther: lijie

     * @date: 2021/6/26 下午 12:04:38
     * @return: void
     */
    @Scheduled(cron = "0/5 * * * * ?")
    public void times() throws AlipayApiException {
        //查询到所有未支付的订单
        List<SmallMiGoodsOrder> smallMiGoodsOrders = payMentService.getorderStatus();
        for (SmallMiGoodsOrder smallMiGoodsOrder : smallMiGoodsOrders) {
            //判断所有查询的订单中是使用支付宝支付的
            if (smallMiGoodsOrder.getPattern_of_payment().equals("Alipay")){
                //创建底层阿里的实体类，把未支付订单类型是支付宝的订单号放进入
                AlipayTradeQueryModel alipayTradeQueryModel = new AlipayTradeQueryModel();
                alipayTradeQueryModel.setOutTradeNo(smallMiGoodsOrder.getOrder_number());
                //这个方法会拿到订单号去支付宝去判断这个订单号是不是已经支付
                AlipayTradeQueryResponse result = AliPayApi.tradeQueryToResponse(alipayTradeQueryModel);
                //支付宝的支付成功凭证是10000，如果拿到的是则说明支付成功了
                if (result.getCode().equals("10000")){
                    //拿到金额
                    String totalAmount = result.getTotalAmount();
                    //金额转类型
                    BigDecimal bigDecimal = new BigDecimal(totalAmount);
                    //订单号
                    String tradeNo = result.getOutTradeNo();
                    //状态码
                    String tradeStatus = result.getTradeStatus();
                    //调用公共方法 进行判断
                    PayMent payMent = new PayMent();
                    payMent.setTradeStatus(tradeStatus);
                    payMent.setOutTradeNo(tradeNo);
                    payMent.setTotalAmount(bigDecimal);
                    payMentService.publicCheckNotifyurl(payMent);
                    System.out.println("修改成功！！！！");
                }
            }
        }
    }
}
